import csv
import struct


def read_csv(file_path):
    labels = []
    with open(file_path, mode='r') as file:
        csv_reader = csv.reader(file)
        next(csv_reader)  # 跳过表头
        for row in csv_reader:
            labels.append(int(row[0]))
    return labels


def write_binary(labels, binary_file_path):
    with open(binary_file_path, 'wb') as file:
        # 写入魔术数和标签数量
        magic_number = 2049  # MNIST数据集中的魔术数
        num_labels = len(labels)
        file.write(struct.pack('>I', magic_number))
        file.write(struct.pack('>I', num_labels))

        # 写入标签数据
        for label in labels:
            file.write(struct.pack('B', label))


if __name__ == "__main__":
    csv_file_path = 't10k-labels.csv'
    binary_file_path = 't10k-labels.idx1-ubyte'

    labels = read_csv(csv_file_path)
    write_binary(labels, binary_file_path)

    print(f"Labels have been written to {binary_file_path}")
